<template>
  <div class="home-container">
    <!-- 顶部导航 -->
    <header class="main-header">
      <div class="logo">
        <span class="logo-text">家庭中控</span>
      </div>
      <button class="notice-btn" @click="showNotice = !showNotice">
        <img src="https://picsum.photos/id/160/24/24" alt="通知" class="icon" />
        <span class="notice-badge" v-if="noticeCount > 0">{{ noticeCount }}</span>
      </button>
    </header>

    <!-- 通知区域（非浮动层） -->
    <div class="notice-toast" v-if="showNotice">
      <div class="toast-item" v-for="(item, i) in notices" :key="i">
        <div class="notice-icon" :class="item.type"></div>
        <div class="notice-content">
          <p class="notice-text">{{ item.text }}</p>
          <p class="notice-time">{{ item.time }}</p>
        </div>
      </div>
      <button class="clear-notice" @click="clearNotices">清空</button>
    </div>

    <!-- 选择器区域 -->
    <div class="selectors">
      <select class="room-select" v-model="activeRoom" @change="handleRoomSelect">
        <option :value="room.id" v-for="room in rooms" :key="room.id">
          {{ room.name }}
        </option>
      </select>
      <select class="category-select" v-model="activeCategory" @change="handleCategorySelect">
        <option :value="category.id" v-for="category in categories" :key="category.id">
          {{ category.name }}
        </option>
      </select>
    </div>

    <!-- 主内容区 -->
    <main class="main-content">
      <!-- 环境状态卡片 -->
      <div class="env-cards">
        <div class="env-card" v-for="(item, i) in envItems" :key="i">
          <div class="env-icon">
            <img :src="item.icon" alt="{{ item.label }}" class="icon" />
          </div>
          <div class="env-info">
            <div class="env-label">{{ item.label }}</div>
            <div class="env-value">{{ item.value }}</div>
            <div class="env-desc">{{ item.desc }}</div>
          </div>
        </div>
      </div>

      <!-- 设备列表 -->
      <div class="devices-section">
        <div class="section-header">
          <h3 class="section-title">设备控制</h3>
          <span class="device-count">{{ tableData.length }} 台设备</span>
        </div>
        <div class="devices-grid">
          <div class="device-card" v-for="(device, i) in tableData" :key="i">
            <div class="device-icon">
              <img :src="getDeviceIcon(device.type)" alt="{{ device.name }}" class="icon" />
            </div>
            <div class="device-info">
              <div class="device-name">{{ device.name }}</div>
              <div class="device-status" :class="device.status">
                {{ device.status === 'online' ? '运行中' : '已关闭' }}
              </div>
              <div class="device-detail">{{ device.detail }}</div>
            </div>
            <label class="switch">
              <el-switch
                :disabled="device.status != 'online'"
                v-model="device.condition"
                @change="change(device)"
              >
              </el-switch>
              <!-- <input
                type="checkbox"
                :checked="device.status === 'offline'"
                @change="handleDeviceChange(device, $event.target.checked)"
              /> -->
              <!-- <span class="slider"></span> -->
            </label>
          </div>
        </div>
      </div>

      <!-- 场景模式 -->
      <div class="scenes-section">
        <h3 class="section-title">智能场景</h3>
        <div class="scenes-grid">
          <button
            class="scene-btn"
            :class="{ 'scene-active': activeScene === scene.id }"
            v-for="(scene, i) in scenes"
            :key="i"
            @click="handleSceneActivate(scene)"
          >
            <img :src="scene.icon" alt="{{ scene.name }}" class="icon" />
            <span class="scene-name">{{ scene.name }}</span>
          </button>
        </div>
      </div>

      <!-- 能源监控（Chart.js图表） -->
      <div class="energy-section">
        <div class="section-header">
          <h3 class="section-title">能源监控</h3>
          <select class="time-select" v-model="energyTimeRange" @change="updateEnergyChart">
            <option value="day">今日</option>
            <option value="week">本周</option>
            <option value="month">本月</option>
          </select>
        </div>
        <div class="energy-chart-container">
          <canvas ref="energyChart"></canvas>
        </div>
      </div>
    </main>

    <!-- 底部常用设备 -->
    <footer class="main-footer">
      <h3 class="section-title">常用设备</h3>
      <div class="favorites-grid">
        <div class="favorite-item" v-for="(device, i) in favoriteDevices" :key="i">
          <div class="favorite-name">{{ device.name }}</div>
          <label class="switch">
            <input
              type="checkbox"
              :checked="device.status === 'on'"
              @change="handleDeviceChange(device, $event.target.checked)"
            />
            <span class="slider"></span>
          </label>
        </div>
      </div>
    </footer>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import Chart from 'chart.js/auto' // 引入Chart.js
import { mqttIndex } from '@/api/mqtt'
import { ElMessage } from 'element-plus'
import { deviceList } from '@/api/device'
import moment from 'moment'

// 状态管理
const showNotice = ref(false)
const noticeCount = ref(3)
const activeRoom = ref(1)
const activeCategory = ref('all')
const activeScene = ref(null)
const energyTimeRange = ref('day')
const energyChart = ref(null)
const query = ref({
  pageNum: 1,
  pageSize: 5,
  name: ''
})
const tableData = ref<any>([])
const total = ref(0)
let energyChartInstance = null
const change = (row: any) => {
  mqttIndex({
    id: row.id,
    condition: row.condition
  }).then((res: any) => {
    if (res.code == 200) {
      ElMessage({
        message: res.message,
        type: 'success'
      })
    } else {
      row.condition = !row.condition
      ElMessage({
        message: res.message,
        type: 'error'
      })
    }
  })
}

const getMenuList = (data = {}) => {
  if (data) {
    query.value = {
      ...query.value,
      ...data
    }
  }
  deviceList({ ...query.value }).then((res: any) => {
    if (res.code == 200) {
      res.data.forEach((item) => {
        item.created_at = moment(item.created_at).format('YYYY-MM-DD HH:mm:ss')
        item.updated_at = moment(item.created_at).format('YYYY-MM-DD HH:mm:ss')
        item.condition = item.condition == 'True' // 设备启动状态
      })
      total.value = res.total || 0
      tableData.value = res.data
    }
  })
}

// 数据定义
const notices = ref([
  { text: '客厅灯光异常关闭', time: '10:23', type: 'warning' },
  { text: '今日用电量已超标', time: '09:15', type: 'danger' },
  { text: '前门已解锁', time: '08:30', type: 'success' }
])

const rooms = ref([
  { id: 1, name: '客厅' },
  { id: 2, name: '主卧' },
  { id: 3, name: '厨房' },
  { id: 4, name: '浴室' }
])

const categories = ref([
  { id: 'all', name: '全部设备' },
  { id: 'light', name: '智能灯光' },
  { id: 'climate', name: '环境控制' },
  { id: 'appliance', name: '家用电器' },
  { id: 'security', name: '安防系统' }
])

const devices = ref([
  { id: 1, roomId: 1, name: '主灯', type: 'light', status: 'on', detail: '亮度 80%' },
  { id: 2, roomId: 1, name: '空调', type: 'climate', status: 'on', detail: '制冷 24°C' },
  { id: 3, roomId: 1, name: '电视', type: 'appliance', status: 'off', detail: '待机中' },
  { id: 4, roomId: 1, name: '窗帘', type: 'appliance', status: 'on', detail: '打开 50%' },
  { id: 5, roomId: 1, name: '摄像头', type: 'security', status: 'on', detail: '录制中' },
  { id: 6, roomId: 2, name: '床头灯', type: 'light', status: 'off', detail: '已关闭' },
  { id: 7, roomId: 2, name: '空调', type: 'climate', status: 'on', detail: '制冷 22°C' },
  { id: 8, roomId: 2, name: '空气净化器', type: 'appliance', status: 'on', detail: '自动模式' },
  { id: 9, roomId: 3, name: '吸顶灯', type: 'light', status: 'on', detail: '亮度 100%' },
  { id: 10, roomId: 3, name: '抽油烟机', type: 'appliance', status: 'on', detail: '强风模式' },
  { id: 11, roomId: 3, name: '冰箱', type: 'appliance', status: 'on', detail: '冷藏 4°C' },
  { id: 12, roomId: 4, name: '浴霸', type: 'appliance', status: 'off', detail: '已关闭' },
  { id: 13, roomId: 4, name: '镜前灯', type: 'light', status: 'off', detail: '已关闭' }
])

const scenes = ref([
  { id: 1, name: '回家模式', icon: 'https://picsum.photos/id/239/32/32' },
  { id: 2, name: '睡眠模式', icon: 'https://picsum.photos/id/240/32/32' },
  { id: 3, name: '离家模式', icon: 'https://picsum.photos/id/241/32/32' },
  { id: 4, name: '影院模式', icon: 'https://picsum.photos/id/242/32/32' }
])

// 计算属性
const currentRoomData = computed(() => {
  const envMap = {
    1: { temp: 24, humidity: 45, airQuality: '优', power: 120, dailyCost: 8.5 },
    2: { temp: 22, humidity: 40, airQuality: '优', power: 60, dailyCost: 3.2 },
    3: { temp: 26, humidity: 50, airQuality: '中', power: 350, dailyCost: 12.8 },
    4: { temp: 28, humidity: 70, airQuality: '中', power: 0, dailyCost: 2.1 }
  }
  return envMap[activeRoom.value] || envMap[1]
})

const envItems = computed(() => [
  {
    label: '环境温度',
    value: `${currentRoomData.value.temp}°C`,
    desc: '舒适区间',
    icon: 'https://picsum.photos/id/119/32/32'
  },
  {
    label: '相对湿度',
    value: `${currentRoomData.value.humidity}%`,
    desc: '正常区间',
    icon: 'https://picsum.photos/id/120/32/32'
  },
  {
    label: '空气质量',
    value: currentRoomData.value.airQuality,
    desc: getAirQualityText(currentRoomData.value.airQuality),
    icon: 'https://picsum.photos/id/121/32/32'
  },
  {
    label: '实时功耗',
    value: `${currentRoomData.value.power}W`,
    desc: `今日 ${currentRoomData.value.dailyCost}元`,
    icon: 'https://picsum.photos/id/122/32/32'
  }
])

const filteredDevices = computed(() => {
  return devices.value.filter((device) => {
    const matchRoom = device.roomId === activeRoom.value
    const matchCategory = activeCategory.value === 'all' || device.type === activeCategory.value
    return matchRoom && matchCategory
  })
})

const favoriteDevices = computed(() => {
  return devices.value.filter((device) => [1, 2, 6, 9].includes(device.id))
})

// 辅助函数
function getAirQualityText(quality) {
  const map = { 优: '良好', 中: '一般', 差: '较差' }
  return map[quality] || quality
}

function getDeviceIcon(type) {
  const icons = {
    light: 'https://picsum.photos/id/139/32/32',
    climate: 'https://picsum.photos/id/140/32/32',
    appliance: 'https://picsum.photos/id/141/32/32',
    security: 'https://picsum.photos/id/142/32/32'
  }
  return icons[type] || 'https://picsum.photos/id/143/32/32'
}

// 设备控制方法
const handleDeviceChange = (device, isOn) => {
  device.status = isOn ? 'on' : 'off'
}

// 场景激活
const handleSceneActivate = (scene) => {
  activeScene.value = scene.id
  switch (scene.id) {
    case 1: // 回家模式
      devices.value.forEach((d) => {
        if (d.type === 'light' || d.type === 'climate') d.status = 'on'
      })
      break
    case 2: // 睡眠模式
      devices.value.forEach((d) => {
        if (d.type === 'light' || (d.type === 'appliance' && d.id !== 8)) d.status = 'off'
      })
      break
    case 3: // 离家模式
      devices.value.forEach((d) => {
        if (d.type !== 'security' && d.id !== 11) d.status = 'off'
      })
      break
    case 4: // 影院模式
      devices.value.forEach((d) => {
        if (d.type === 'light') d.status = 'off'
        if (d.id === 3 || d.id === 4) d.status = 'on'
      })
      break
  }
}

// 选择器变更处理
const handleRoomSelect = () => {
  updateEnergyChart() // 切换房间时更新图表
}

const handleCategorySelect = () => {}

// 通知处理
const clearNotices = () => {
  notices.value = []
  noticeCount.value = 0
}

// 初始化/更新能源图表（Chart.js实现）
const updateEnergyChart = () => {
  if (!energyChart.value) return

  // 销毁旧图表
  if (energyChartInstance) {
    energyChartInstance.destroy()
  }

  // 图表数据
  const { labels, data, unit } = getEnergyData()

  // 创建新图表
  energyChartInstance = new Chart(energyChart.value, {
    type: 'line',
    data: {
      labels: labels,
      datasets: [
        {
          label: `能耗(${unit})`,
          data: data,
          fill: true,
          backgroundColor: 'rgba(59, 130, 246, 0.1)',
          borderColor: '#3b82f6',
          tension: 0.4,
          pointBackgroundColor: '#3b82f6',
          pointRadius: 4,
          pointHoverRadius: 6
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: 'top',
          labels: {
            usePointStyle: true,
            boxWidth: 8
          }
        },
        tooltip: {
          mode: 'index',
          intersect: false
        }
      },
      scales: {
        x: {
          grid: {
            display: false
          }
        },
        y: {
          beginAtZero: true,
          grid: {
            color: 'rgba(0, 0, 0, 0.05)'
          },
          ticks: {
            callback: (value) => `${value}${unit}`
          }
        }
      }
    }
  })
}

// 获取能源数据
function getEnergyData() {
  switch (energyTimeRange.value) {
    case 'day':
      return {
        labels: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00', '现在'],
        data: [80, 60, 320, 150, 280, 420, 120],
        unit: 'W'
      }
    case 'week':
      return {
        labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        data: [5.2, 4.8, 6.1, 5.5, 7.2, 8.5, 6.3],
        unit: 'kWh'
      }
    case 'month':
      return {
        labels: ['1日', '5日', '10日', '15日', '20日', '25日', '30日'],
        data: [80, 75, 90, 85, 100, 95, 88],
        unit: 'kWh'
      }
    default:
      return { labels: [], data: [], unit: '' }
  }
}

// 生命周期
onMounted(() => {
  // 初始化图表
  updateEnergyChart()

  // 监听窗口大小变化
  window.addEventListener('resize', updateEnergyChart)
  // 获取设备列表
  getMenuList()
})

onUnmounted(() => {
  window.removeEventListener('resize', updateEnergyChart)
  if (energyChartInstance) {
    energyChartInstance.destroy()
  }
})

// 监听时间范围变化更新图表
watch(energyTimeRange, updateEnergyChart)
</script>

<style scoped>
/* 基础样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
}

.home-container {
  height: 100vh;
  background-color: #f8fafc;
  color: #334155;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.icon {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

/* 顶部导航 */
.main-header {
  height: 55px;
  background-color: #fff;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.logo-text {
  font-size: 18px;
  font-weight: 600;
  color: #3b82f6;
}

.notice-btn {
  position: relative;
  width: 36px;
  height: 36px;
  border-radius: 8px;
  background-color: transparent;
  border: none;
  cursor: pointer;
}

.notice-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  width: 20px;
  height: 20px;
  background-color: #ff4d4f;
  color: white;
  border-radius: 50%;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 通知区域 */
.notice-toast {
  background-color: #fff;
  border-bottom: 1px solid #e2e8f0;
  padding: 10px 15px;
  max-height: 180px;
  overflow-y: auto;
  transition: all 0.3s;
}

.toast-item {
  display: flex;
  padding: 8px 0;
  border-bottom: 1px solid #f1f5f9;
}

.toast-item:last-child {
  border-bottom: none;
}

.notice-icon {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 10px;
  margin-top: 6px;
}

.notice-icon.warning {
  background-color: #faad14;
}
.notice-icon.danger {
  background-color: #ff4d4f;
}
.notice-icon.success {
  background-color: #52c41a;
}

.notice-text {
  font-size: 14px;
  margin-bottom: 4px;
}
.notice-time {
  font-size: 12px;
  color: #94a3b8;
}

.clear-notice {
  width: 100%;
  padding: 8px;
  background-color: transparent;
  border: none;
  color: #3b82f6;
  cursor: pointer;
  font-size: 14px;
}

/* 选择器区域 */
.selectors {
  display: flex;
  gap: 10px;
  padding: 10px 15px;
  background-color: #fff;
  border-bottom: 1px solid #e2e8f0;
}

.room-select,
.category-select {
  flex: 1;
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
  background-color: #f8fafc;
  color: #334155;
  font-size: 14px;
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%2364748b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 10px center;
}

/* 主内容区 */
.main-content {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #f8fafc;
}

/* 环境卡片 */
.env-cards {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  margin-bottom: 20px;
}

.env-card {
  background-color: #fff;
  border-radius: 10px;
  border: 1px solid #e2e8f0;
  padding: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.env-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background-color: #f1f5f9;
  padding: 8px;
  flex-shrink: 0;
}

.env-label {
  font-size: 13px;
  color: #64748b;
}
.env-value {
  font-size: 20px;
  font-weight: 600;
  margin: 5px 0;
}
.env-desc {
  font-size: 12px;
  color: #94a3b8;
}

/* 设备列表 */
.devices-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #334155;
}
.device-count {
  color: #64748b;
  font-size: 13px;
}

.devices-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.device-card {
  background-color: #fff;
  border-radius: 10px;
  border: 1px solid #e2e8f0;
  padding: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.device-icon {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  background-color: #f1f5f9;
  padding: 6px;
  flex-shrink: 0;
}

.device-info {
  flex: 1;
  min-width: 0;
}
.device-name {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.device-status {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 10px;
  display: inline-block;
  margin-bottom: 5px;
}

.device-status.on {
  background-color: rgba(82, 196, 26, 0.1);
  color: #52c41a;
}

.device-status.off {
  background-color: rgba(100, 116, 139, 0.1);
  color: #64748b;
}

.device-detail {
  font-size: 12px;
  color: #94a3b8;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 开关样式 */
.switch {
  position: relative;
  display: inline-block;
  width: 40px;
  height: 20px;
  margin-left: auto;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #e2e8f0;
  transition: 0.4s;
  border-radius: 34px;
}

.slider:before {
  position: absolute;
  content: '';
  height: 14px;
  width: 14px;
  left: 3px;
  bottom: 3px;
  background-color: white;
  transition: 0.4s;
  border-radius: 50%;
}

input:checked + .slider {
  background-color: #3b82f6;
}
input:checked + .slider:before {
  transform: translateX(20px);
}

/* 场景模式 */
.scenes-section {
  margin-bottom: 20px;
}

.scenes-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.scene-btn {
  background-color: #f1f5f9;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 10px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  transition: all 0.2s;
}

.scene-btn:hover {
  background-color: #e0f2fe;
  border-color: #bae6fd;
}

.scene-btn.scene-active {
  background-color: #3b82f6;
  border-color: #3b82f6;
  color: white;
}

.scene-btn .icon {
  width: 28px;
  height: 28px;
}
.scene-name {
  font-size: 13px;
}

/* 能源监控图表 */
.energy-section {
  margin-bottom: 20px;
}

.time-select {
  background-color: #f1f5f9;
  color: #334155;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  padding: 5px 10px;
  font-size: 13px;
  cursor: pointer;
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%2364748b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 10px center;
}

.energy-chart-container {
  background-color: #fff;
  border-radius: 10px;
  border: 1px solid #e2e8f0;
  padding: 15px;
  height: 220px;
}

/* 底部常用设备 */
.main-footer {
  background-color: #fff;
  border-top: 1px solid #e2e8f0;
  padding: 15px;
}

.favorites-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.favorite-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #f1f5f9;
  border-radius: 8px;
}

.favorite-name {
  font-size: 13px;
  color: #334155;
}

/* 响应式适配 */
@media (max-width: 375px) {
  .env-cards,
  .devices-grid,
  .scenes-grid,
  .favorites-grid {
    grid-template-columns: 1fr;
  }

  .selectors {
    flex-direction: column;
  }
}
</style>
